package com.lanyuan.thrid.wechat.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;

import com.lanyuan.thrid.wechat.client.LocalHttpClient;

public class Api {

	/**
	 * 获取access_token
	 * 
	 * @param appid
	 * @param secret
	 * @return
	 */
	public static Map<String, String> token() {
		HttpUriRequest httpUriRequest = RequestBuilder.post().setUri("https://api.weixin.qq.com/cgi-bin/token")
				.addParameter("grant_type", "client_credential").addParameter("appid", Constants.APPID)
				.addParameter("secret", Constants.APPSECRET).build();
		return LocalHttpClient.executeJsonResult(httpUriRequest);
	}

	/**
	 * 获取用户基本信息
	 * 
	 * @param access_token
	 * @param openid
	 * @return
	 */
	public static Map<String, String> userInfo(String access_token, String openid) {
		HttpUriRequest httpUriRequest = RequestBuilder.get().setUri("https://api.weixin.qq.com/cgi-bin/user/info")
				.addParameter("access_token", access_token).addParameter("openid", openid)
				.addParameter("lang", "zh_CN").build();
		return LocalHttpClient.executeJsonResult(httpUriRequest);
	}

	/**
	 * 通过code换取网页授权access_token
	 * 
	 * @param appid
	 * @param secret
	 * @param code
	 * @return
	 */
	public static Map<String, String> oauth2AccessToken(String code) {
		HttpUriRequest httpUriRequest = RequestBuilder.post()
				.setUri("https://api.weixin.qq.com/sns/oauth2/access_token").addParameter("appid", Constants.APPID)
				.addParameter("secret", Constants.APPSECRET).addParameter("code", code)
				.addParameter("grant_type", "authorization_code").build();
		return LocalHttpClient.executeJsonResult(httpUriRequest);
	}

	/**
	 * 生成网页授权 URL (第三方平台开发)
	 * 
	 * @param appid
	 * @param redirect_uri 自动URLEncoder
	 * @param snsapi_userinfo
	 * @param state 可以为空
	 * @return
	 */
	public static String connectOauth2Authorize(String redirect_uri, boolean snsapi_userinfo) {
		try {
			StringBuilder sb = new StringBuilder();
			sb.append("https://open.weixin.qq.com/connect/oauth2/authorize?").append("appid=").append(Constants.APPID)
					.append("&redirect_uri=").append(URLEncoder.encode(redirect_uri, "utf-8"))
					.append("&response_type=code").append("&scope=")
					.append(snsapi_userinfo ? "snsapi_userinfo" : "snsapi_base").append("&state=")
					.append("state=STATE").append("#wechat_redirect");
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 统一下单
	 * 
	 * @param unifiedorder
	 * @param key
	 * @return
	 */
	public static Map<String, String> payUnifiedorder(Map<String, String> map, String key) {
		if (key != null) {
			String sign = SignatureUtil.generateSign(map, key);
			map.put("sign", sign);
		}
		String unifiedorderXML = XMLConverUtil.convertToXML(map);
		HttpUriRequest httpUriRequest = RequestBuilder.post()
				.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_XML.toString()))
				.setUri("https://api.mch.weixin.qq.com/pay/unifiedorder")
				.setEntity(new StringEntity(unifiedorderXML, Charset.forName("utf-8"))).build();
		return LocalHttpClient.executeXmlResult(httpUriRequest);
	}

	/**
	 * 创建菜单
	 * 
	 * @param access_token
	 * @param menuJson 菜单json 数据 例如{\
	 *            "button\":[{\"type\":\"click\",\"name\":\"今日歌曲\",\"key\":\"V1001_TODAY_MUSIC\"},{\"type\":\"click\",\"name\":\"歌手简介\",\"key\":\"V1001_TODAY_SINGER\"},{\"name\":\"菜单\",\"sub_button\":[{\"type\":\"view\",\"name\":\"搜索\",\"url\":\"http://www.soso.com/\"},{\"type\":\"view\",\"name\":\"视频\",\"url\":\"http://v.qq.com/\"},{\"type\":\"click\",\"name\":\"赞一下我们\",\"key\":\"V1001_GOOD\"}]
	 *            }
	 *            ]
	 *            }
	 * @return
	 */
	public static Map<String, String> menuCreate(String access_token, String menuJson) {
		HttpUriRequest httpUriRequest = RequestBuilder.post()
				.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()))
				.setUri("https://api.weixin.qq.com/cgi-bin/menu/create").addParameter("access_token", access_token)
				.setEntity(new StringEntity(menuJson, Charset.forName("utf-8"))).build();
		return LocalHttpClient.executeJsonResult(httpUriRequest);
	}

	/**
	 * 删除菜单
	 * 
	 * @param access_token
	 * @return
	 */
	public static Map<String, String> menuDelete(String access_token) {
		HttpUriRequest httpUriRequest = RequestBuilder.post().setUri("https://api.weixin.qq.com/cgi-bin/menu/delete")
				.addParameter("access_token", access_token).build();
		return LocalHttpClient.executeJsonResult(httpUriRequest);
	}

}
